package com.cgs.query.service.impl

import com.cgs.query.domain.ProjectLockLog
import com.cgs.query.domain.QueryProject
import com.cgs.query.service.IProjectLockLogService
import com.cgs.query.service.jpa.ProjectLockLogRepository
import kotlinx.coroutines.experimental.launch
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class ProjectLockLogServiceImpl : IProjectLockLogService {

    @Autowired
    private lateinit var lockLogRepository: ProjectLockLogRepository

    override fun save(oldQueryProject: QueryProject, newQueryProject: QueryProject, userId: String?) {
        if (oldQueryProject.lockType != newQueryProject.lockType) {
            val projectLockLog = ProjectLockLog().apply {
                this.userId = userId
                oldLockType = oldQueryProject.lockType
                newLockType = newQueryProject.lockType
                projectName = newQueryProject.name
            }
            launch {
                lockLogRepository.save(projectLockLog)
            }
        }
    }

    override fun delete(name: String) {
        launch {
            lockLogRepository.deleteByProjectName(name)
        }
    }

    override fun findByName(name: String): List<ProjectLockLog>? {
        return lockLogRepository.findByProjectNameOrderByTimeDesc(name)
    }
}
